package org.seven.jrdp.web.mgt.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.seven.jrdp.biz.core.service.MgtCoreService;
import org.seven.jrdp.biz.sys.model.SysUkey;
import org.seven.jrdp.biz.sys.service.SysUkeyService;
import org.seven.jrdp.commons.config.ParamConfig;
import org.seven.jrdp.commons.constant.GlobalContants;
import org.seven.jrdp.commons.model.Result;
import org.seven.jrdp.commons.plugin.ukey.UkeyPlugin;
import org.seven.jrdp.commons.shiro.authc.UserToken;
import org.seven.jrdp.commons.shiro.authc.UserType;
import org.seven.jrdp.commons.util.DateTimeUtils;
import org.seven.jrdp.commons.util.RsaUtils;
import org.seven.jrdp.commons.util.ShiroUtils;
import org.seven.jrdp.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/mgt/core")
public class MgtCoreController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private MgtCoreService mgtCoreService;
	@Autowired
	private SysUkeyService sysUkeyService;

	@GetMapping("/login")
	public String login(HttpSession session) {
		if (Boolean.valueOf(ParamConfig.ukey)) {
			session.setAttribute(GlobalContants.SESSION_UKEY_UUID, StringUtils.uuid());
			return "mgt/core/login_ukey";
		} else {
			return "mgt/core/login";
		}
	}

	@PostMapping("/login")
	public String login(String account, String password, String ukey, String enc, HttpSession session) {
		try {
			account = RsaUtils.decrypt(account, ParamConfig.privateKey);
			password = RsaUtils.decrypt(password, ParamConfig.privateKey);
			if (Boolean.valueOf(ParamConfig.ukey)) {
				SysUkey sysUkey = sysUkeyService.getByAccount(account);
				if (sysUkey == null) {
					throw new UnsupportedTokenException();
				}
				if (!sysUkey.getId().equals(ukey)) {
					throw new UnsupportedTokenException();
				}
				if (!UkeyPlugin.decrypt(enc, sysUkey.getUserId()).equals(session.getAttribute(GlobalContants.SESSION_UKEY_UUID))) {
					throw new UnsupportedTokenException();
				}
			}
			Subject subject = SecurityUtils.getSubject();
			UserToken token = new UserToken(account, password, UserType.MGT);
			subject.login(token);
		} catch (Exception e) {
			logger.error("登录异常", e);
			return "redirect:/mgt/core/login?error=true";
		}
		return "redirect:/mgt/core/main";
	}

	@RequestMapping("/main")
	public String main(HttpServletRequest request) {
		Session session = ShiroUtils.getSession();
		session.setAttribute(GlobalContants.SESSION_TODAY, DateFormatUtils.format(DateTimeUtils.getDate(), GlobalContants.PATTERN_DATE));
		session.setAttribute(GlobalContants.SESSION_MONTH_FIRST, DateFormatUtils.format(DateTimeUtils.getMonthFirst(), GlobalContants.PATTERN_DATE));
		session.setAttribute(GlobalContants.SESSION_MONTH_LAST, DateFormatUtils.format(DateTimeUtils.getMonthLast(), GlobalContants.PATTERN_DATE));
		return "mgt/core/main";
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/mgt/core/login";
	}

	@RequestMapping("/error/{view}")
	public String error(@PathVariable String view) {
		return "mgt/core/error/" + view;
	}

	@GetMapping("/password")
	public String password() {
		return "mgt/core/password";
	}

	@PostMapping("/password")
	@ResponseBody
	public Result password(String oldPassword, String newPassword) {
		oldPassword = RsaUtils.decrypt(oldPassword, ParamConfig.privateKey);
		newPassword = RsaUtils.decrypt(newPassword, ParamConfig.privateKey);
		mgtCoreService.password(ShiroUtils.getUser().getId(), oldPassword, newPassword);
		return Result.SUCCESS;
	}
}